import { HYEventStore} from 'hy-event-store'
import {
  getMusicInfo,
  getMusicLyric
} from "../service/api";
import changeLyricStructure from '../utils/changeLyricStructure'
const audioCTX = wx.createInnerAudioContext()

export const audioStore = new HYEventStore({
  state: {
    id: '',
    musicInfo: {},
    lyricList: [],
    totalTime: 0,
    status: false,

    currentTime: 0,
    currentLyricIndex: 0,

    songsPlayList: [], // 播放列表
    currentPlayIndex: 0, // 当前播放下标

    playModuleIndex: 0 // 播放模式
  },
  actions: {
    getMusicInfoAction(ctx, id, replace = false) {
      audioCTX.offCanplay()
      audioCTX.offEnded()
      if (ctx.id == id && !replace) {
        audioCTX.play()
        return
      } else if (replace) {
        audioCTX.pause()
        audioCTX.seek(0)
        ctx.currentTime= 0
        ctx.currentLyricIndex= 0
        // audioCTX.play()
        return 
      } else { // id不同,重置播放信息
        ctx.id = id
        ctx.musicInfo = {}
        ctx.lyricList = []
        ctx.totalTime = 0
        ctx.currentTime = 0
        ctx.currentLyricIndex = 0
        ctx.status = false
      }

      /**
       * 资源请求
       */
      getMusicInfo(id).then(e => {
        const musicInfo = e.songs[0]
        ctx.musicInfo = musicInfo
        ctx.totalTime =  musicInfo.dt
      })
      getMusicLyric(id).then(e => {
        const {
          lrc: {
            lyric
          }
        } = e
        const lyricList = changeLyricStructure(lyric)
        ctx.lyricList = lyricList
      })
      /**
       * music设置
       */
      audioCTX.src = `https://music.163.com/song/media/outer/url?id=${ctx.id}.mp3`
      audioCTX.autoplay = true
      audioCTX.onCanplay(() => {
        audioCTX.play()
        ctx.status = true
      })
      this.dispatch('setupMusicInfoAction')
    },
    setupMusicInfoAction(ctx) {
      audioCTX.onTimeUpdate(() => {
        let currentTime = audioCTX.currentTime * 1000
        ctx.currentTime = currentTime
  
        //找到播放时间对应的歌词
        const currentLyricIndex = ctx.lyricList.findIndex((e, index) => {
          if (index == ctx.lyricList.length - 1) return e
          return currentTime >= e.time && currentTime < ctx.lyricList[index + 1].time
        })
        if (ctx.currentLyricIndex != currentLyricIndex) {
          ctx.currentLyricIndex = currentLyricIndex
        }
      })
      audioCTX.onEnded(() => {
        this.dispatch('changCurrentPlaySong', 'next')
      })
    },
    changeAudioStatus(ctx, status) {
      if(status) {
        audioCTX.pause()
      } else {
        audioCTX.play()
      }
      ctx.status = !status
    },
    changePlayModuleIndexAction(ctx, playModuleIndex) {
      if (++playModuleIndex > 2) {
        ctx.playModuleIndex = 0
      }else {
        ctx.playModuleIndex++
      }
    },
    changCurrentPlaySong(ctx, type) {
      console.log('offCanplay')
      // 0:'order', // 列表循环
      // 1:'repeat', // 单曲循环
      // 2:'random' // 乱序
      if (ctx.songsPlayList.length == 0 || ctx.songsPlayList.length == 1) {
        this.dispatch('getMusicInfoAction', ctx.id, true)
        return 
      } // 播放列表为0或为1.直接重置信息
      let currentPlayIndex
      if (type == 'pre') {
        currentPlayIndex = ctx.currentPlayIndex - 1
      } else {
        currentPlayIndex = ctx.currentPlayIndex + 1
      }
      if (currentPlayIndex >= ctx.songsPlayList.length) {
        currentPlayIndex = 0
      } else if (currentPlayIndex < 0) {
        currentPlayIndex = ctx.songsPlayList.length - 1
      }
      console.log(currentPlayIndex)
      switch (ctx.playModuleIndex) {
        case 0:
            this.dispatch('getMusicInfoAction', ctx.songsPlayList[currentPlayIndex].id);
            break;
        case 1:
          this.dispatch('getMusicInfoAction', ctx.id, true);
          break;
        case 2:
          currentPlayIndex = ctx.currentPlayIndex
          while(currentPlayIndex == ctx.currentPlayIndex){
            currentPlayIndex = Math.floor(Math.random() * ctx.songsPlayList.length)
          };
          this.dispatch('getMusicInfoAction', ctx.songsPlayList[currentPlayIndex].id);
          break;
      }
      ctx.currentPlayIndex = currentPlayIndex
    }
  }
})

export default audioCTX